package com.njwb.day15.zqzb.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class AddStudentTest {
    public static void main(String[] args) {
        String name = "赵云";
        int age = 23 ;
        String address= "南京";
        //构建连接对象
        Connection connection= null ;
        //命令器
        Statement statement= null ;
        try {
            //1、加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2、获取连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mytest","root","root");
            //3、创建命令器
            statement = connection.createStatement();
            //4、准备待执行的sql语句
            String sql = "insert into tb_student(sname,age,address) values ('"+name+"',"+age+",'"+address+"')";
            //5.执行sql语句
            statement.execute(sql);
            System.out.println("数据添加成功！！！");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //6、关闭资源 （倒着关闭）
            if(statement!=null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(connection!=null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}
